from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework import serializers
from community.models import *


class ArticleSerializer(ModelSerializer):
    class Meta:
        model = Article
        exclude = ['is_delete']


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = SerializerMethodField()

    class Meta:
        model = Comment
        fields = '__all__'

    def get_reply_username(self, comment):
        try:
            user = Comment.objects.get(id=comment.reply_comment).user
            reply_name = user.first_name
        except:
            reply_name = None
        return reply_name


class CommentHandlerSerializer(ModelSerializer):
    son_comment = SerializerMethodField()
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'

    def get_son_comment(self, comment):
        # 查询所有parent_comment为level为1的评论的id的评论
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()
        return data
